package com.mars.designpatterns.proxy.dynamicproxy;

import com.mars.designpatterns.proxy.Order;
import com.mars.designpatterns.proxy.db.DataSourceContextHolder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * author by: mars
 * Date: 2020/3/8 22:03
 * Description: 动态代理
 */
public class OrderServiceDynamicProxy implements InvocationHandler {

    private Object target;//目标对象

    public OrderServiceDynamicProxy(Object target) {
        this.target = target;
    }

    // 绑定,创建代理对象
    public Object bind(){
        // 获取目标类的class
        Class cls = target.getClass();
        // 生成一个对象
        return Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),this);

    }

    /**
     *
     * @Author mars
     * @Description
     * @Date 2020/3/8 22:11
     * @param proxy
     * @param method 增强的方法对象
     * @param args 增强方法的参数
     * @return java.lang.Object
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 从args获取对象
        Object argObject = args[0];
        beforeMethod(argObject);
        // 设置要被增强的返回值
        Object object = method.invoke(target,args);
        afterMethod();
        return object;
    }

    private void beforeMethod(Object obj) {
        int userId = 0;
        System.out.println("动态代理 before code");
        // 判断是否为order对象
        if (obj instanceof Order) {
            Order order = (Order)obj;
            userId = order.getUserId();
        }
        int dbRouter = userId % 2;
        System.out.println("动态代理分配到【db"+dbRouter+"】处理数据");
        DataSourceContextHolder.setDBType("db" + dbRouter);
    }

    private void afterMethod() {
        System.out.println("动态代理 after code");
    }
}
